package com.sj.uabrowser.mvp.menu.view.fragment;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.classic.common.MultipleStatusView;
import com.orhanobut.logger.Logger;
import com.sj.uabrowser.R;
import com.sj.uabrowser.db.FileInfo;
import com.sj.uabrowser.db.ThreadInfo;
import com.sj.uabrowser.db.gen.FileInfoDao;
import com.sj.uabrowser.db.gen.ThreadInfoDao;
import com.sj.uabrowser.framework.BasePresenter;
import com.sj.uabrowser.framework.LazyLoadFragment;
import com.sj.uabrowser.mvp.menu.service.DownloadService;
import com.sj.uabrowser.mvp.menu.view.act.DownloadAct;
import com.sj.uabrowser.mvp.menu.view.adp.DownloadingAdp;
import com.vondear.rxui.view.dialog.RxDialogSureCancel;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 */
public class DownloadingFragment extends LazyLoadFragment {


    private static DownloadingFragment sDownloadingFragment;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.multipleStatusView)
    MultipleStatusView multipleStatusView;
    @BindView(R.id.ll_bottom_edit)
    LinearLayout llBottomEdit;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    private FileInfoDao mDao;
    private ThreadInfoDao mThreadInfoDao;
    List<FileInfo> fileList = new ArrayList<>();
    private DownloadingAdp adp;
    private boolean isEdit = false;

    public static DownloadingFragment getInstance(String title) {
        if (sDownloadingFragment == null) {
            sDownloadingFragment = new DownloadingFragment();
            Bundle bundle = new Bundle();
            bundle.putString("title", title);
            sDownloadingFragment.setArguments(bundle);
        }
        return sDownloadingFragment;
    }


    @Override
    protected int setContentView() {
        return R.layout.fragment_downloading;
    }

    @Override
    protected void lazyLoad() {
        fileList.clear();
        fileList.addAll(mDao.queryRaw("where finished < length"));//
        Set<String> parentDatas = new HashSet<>();
        for (int i = 0; i < fileList.size(); i++) {
            FileInfo bean = fileList.get(i);
            long date = bean.getDate();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String time = sdf.format(date);
            if (!parentDatas.contains(time)) {
                bean.setTime(time);
                parentDatas.add(time);
            }else{
                bean.setTime("");
            }
        }
        Logger.e("downloading count = "+fileList.size());
        isEdit = false;
        ((DownloadAct)act).tvEdit.setText("管理");
        adp.notifyDataSetChanged();
        if(fileList.size()==0){
            ((DownloadAct)act).tvEdit.setText("");
            multipleStatusView.showEmpty();
            onBackMain();
        }
    }



    @Override
    public BasePresenter createPresenter() {
        return null;
    }

    @Override
    public void setView() {
        mDao = daoSession.getFileInfoDao();
        mThreadInfoDao = daoSession.getThreadInfoDao();
        rv.setLayoutManager(new LinearLayoutManager(act));
        adp = new DownloadingAdp(R.layout.common_list_item_downloading, fileList);
        rv.setAdapter(adp);
        adp.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                FileInfo fileInfo = fileList.get(position);
                if(!isEdit) {
                    fileInfo.setDownloading(!fileInfo.getIsDownloading());
                    Intent intent = new Intent(act, DownloadService.class);
                    intent.setAction(fileInfo.isDownloading() ? DownloadService.ACTION_START : DownloadService.ACTION_STOP);
                    intent.putExtra("fileInfo", fileInfo);
                    act.startService(intent);
                    updateAdpUpdate(fileInfo.getUrl(), fileInfo.getFileName(), fileInfo.getFinished());
                }else{
                    fileInfo.setChecked(!fileInfo.isChecked());
                    CheckBox cb = view.findViewById(R.id.cb);
                    cb.setChecked(fileInfo.isChecked());
                }
            }

        });
    }

    public void updateAdpUpdate(String url,String filename,long progress){
        Logger.e("progress:"+progress);
        FileInfo fileInfo = null;
        for (int i = 0; i < fileList.size(); i++) {
            if(TextUtils.equals(url,fileList.get(i).getUrl())&&TextUtils.equals(filename,fileList.get(i).getFileName())){
                fileInfo = fileList.get(i);
                fileInfo.setFinished(progress);
                if(progress==fileInfo.getLength()){
                    fileList.remove(fileInfo);
                    if(fileList.size()==0){
                        multipleStatusView.showEmpty();
                        onBackMain();
                    }
                }
                adp.notifyDataSetChanged();
                break;
            }
        }

    }

    @Override
    public void setData() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(DownloadService.ACTION_UPDATE);
        filter.addAction(DownloadService.ACTION_FINISH);
        act.registerReceiver(receiver,filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        act.unregisterReceiver(receiver);
    }

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent!=null){
                String action = intent.getAction();
                if(TextUtils.equals(action,DownloadService.ACTION_UPDATE)){
                    long progress = intent.getLongExtra("finished",0L);
                    String url = intent.getStringExtra("url");
                    String filename = intent.getStringExtra("filename");
                    updateAdpUpdate(url,filename,progress);
                }else if(TextUtils.equals(action,DownloadService.ACTION_FINISH)){
                    FileInfo fileInfo = (FileInfo) intent.getSerializableExtra("fileInfo");
                    updateAdpUpdate(fileInfo.getUrl(),fileInfo.getFileName(),fileInfo.getFinished());
                    Toast.makeText(act,fileInfo.getFileName()+"下载完成！",Toast.LENGTH_SHORT).show();

                    if(adp!=null)adp.notifyDataSetChanged();
                }
            }
        }
    };

    protected void onBackMain() {
        View tvBackMain = multipleStatusView.findViewById(R.id.tv_back_main);
        if(tvBackMain!=null) tvBackMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startIconAnim(v);
                act.finish();
            }
        });
    }
    
    public void onAdmin(){
        isEdit = !isEdit;
        adp.setEdit(isEdit);
        if (!isEdit) setCancelStatus();
        ((DownloadAct)act).tvEdit.setText(isEdit ? "取消" : "编辑");
        llBottomEdit.setVisibility(isEdit ? View.VISIBLE : View.GONE);
        for (int i = 0; i < fileList.size(); i++) {
            FileInfo fileInfo = fileList.get(i);
            fileInfo.setDownloading(false);
            Intent intent = new Intent(act, DownloadService.class);
            intent.setAction(fileInfo.isDownloading() ? DownloadService.ACTION_START : DownloadService.ACTION_STOP);
            intent.putExtra("fileInfo", fileInfo);
            act.startService(intent);
            updateAdpUpdate(fileInfo.getUrl(), fileInfo.getFileName(), fileInfo.getFinished());
        }
    }

    @OnClick({R.id.tv_confirm, R.id.tv_delete})
    public void onEdit(View view) {
        startIconAnim(view);
        switch (view.getId()) {
            case R.id.tv_confirm://全选
                isSelectedAll = !isSelectedAll;
                tvConfirm.setText(isSelectedAll ? "不选" : "全选");
                for (int i = 0; i < fileList.size(); i++) {
                    fileList.get(i).setChecked(isSelectedAll);
                }
                adp.notifyDataSetChanged();
                break;
            case R.id.tv_delete://删除
                int count = 0;
                for (int i = 0; i < fileList.size(); i++) {
                    if(fileList.get(i).isChecked())count++;
                }
                if(count==0){
                    showToast("没有选择项，无法删除！");
                    return;
                }
                RxDialogSureCancel rxDialogSureCancel = new RxDialogSureCancel(act);
                rxDialogSureCancel.getTitleView().setVisibility(View.GONE);
                rxDialogSureCancel.setContent("确定要删除"+count+"项吗？");
                rxDialogSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        deleteDatas();
                        rxDialogSureCancel.dismiss();
                    }
                });
                rxDialogSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        rxDialogSureCancel.dismiss();
                    }
                });
                rxDialogSureCancel.show();
                break;
        }

    }

    private void deleteDatas() {
        List<FileInfo> removeDatas = new ArrayList<>();
        for (int i = 0; i < fileList.size(); i++) {
            FileInfo bean = fileList.get(i);
            List<ThreadInfo> threadInfos = mThreadInfoDao.queryRaw("where url = ? and filename = ?",new String[]{bean.getUrl(),bean.getFileName()});
            List<ThreadInfo> removeThreadInfos = new ArrayList<>();
            for (int j = 0; j < threadInfos.size(); j++) {
                removeThreadInfos.add(threadInfos.get(j));
            }
            threadInfos.removeAll(removeThreadInfos);
            if (bean.isChecked()) {
                removeDatas.add(bean);
            }
        }
        fileList.removeAll(removeDatas);
        for (int i = 0; i < removeDatas.size(); i++) {
            FileInfo bean = removeDatas.get(i);
            if (bean.isChecked()) {
               mDao.delete(bean);
            }
        }
        setCancelStatus();
    }

    private boolean isSelectedAll = false;

    private void setCancelStatus() {
        for (int i = 0; i < fileList.size(); i++) {
            fileList.get(i).setChecked(false);
        }
        isEdit = false;
        adp.setEdit(isEdit);
        adp.notifyDataSetChanged();
        llBottomEdit.setVisibility(View.GONE);
        ((DownloadAct)act).tvEdit.setText(fileList.size() > 0 ? "编辑" : "");
        if(fileList.size()==0){
            multipleStatusView.showEmpty();
            onBackMain();
        }
    }

}
